package com.boot.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.boot.dto.AssignPermissionDTO;
import com.boot.entity.Result;
import com.boot.entity.SysPermission;
import com.boot.entity.SysRolePermission;
import com.boot.service.ISysPermissionService;
import com.boot.service.ISysRolePermissionService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/sys-role-permission")
public class SysRolePermissionController {

    @Resource
    private ISysRolePermissionService rolePermissionService;

    @Resource
    private ISysPermissionService permissionService;

    /**
     * 查询角色已分配的权限 ID 列表
     */
    @GetMapping("/role/{roleId}")
    public Result<List<Long>> getPermissionsByRole(@PathVariable Long roleId) {
        List<Long> permissionIds = rolePermissionService.list(
                        Wrappers.<SysRolePermission>lambdaQuery()
                                .eq(SysRolePermission::getRoleId, roleId))
                .stream()
                .map(SysRolePermission::getPermissionId)
                .collect(Collectors.toList());
        return Result.success(permissionIds);
    }

    /**
     * 分配权限给角色（覆盖式）
     */
    @PostMapping("/assign")
    public Result<String> assignPermissions(@Valid @RequestBody AssignPermissionDTO dto) {
        Long roleId = dto.getRoleId();
        List<Long> permissionIds = dto.getPermissionIds();

        rolePermissionService.remove(
                Wrappers.<SysRolePermission>lambdaQuery().eq(SysRolePermission::getRoleId, roleId));

        if (permissionIds.isEmpty()) {
            return Result.success("权限已清空");
        }

        List<SysRolePermission> list = permissionIds.stream().map(permId -> {
            SysRolePermission rp = new SysRolePermission();
            rp.setRoleId(roleId);
            rp.setPermissionId(permId);
            return rp;
        }).collect(Collectors.toList());

        if (rolePermissionService.saveBatch(list)) {
            return Result.success("权限分配成功");
        }
        return Result.fail("分配失败");
    }

    /**
     * 获取角色对应的权限目录树（前端菜单用）
     */
    @GetMapping("/tree/role/{roleId}")
    public Result<List<SysPermission>> getTreeByRole(@PathVariable Long roleId) {
        // 获取该角色所有权限 ID
        List<Long> permissionIds = rolePermissionService.list(
                        Wrappers.<SysRolePermission>lambdaQuery()
                                .eq(SysRolePermission::getRoleId, roleId))
                .stream()
                .map(SysRolePermission::getPermissionId)
                .collect(Collectors.toList());

        if (permissionIds.isEmpty()) {
            return Result.success(new ArrayList<>());
        }

        // 查询这些权限并构建树
        List<SysPermission> allPerms = permissionService.listByIds(permissionIds);
        List<SysPermission> tree = buildTree(allPerms, 0L);
        return Result.success(tree);
    }

    /**
     * 构建权限树结构
     */
    private List<SysPermission> buildTree(List<SysPermission> all, Long parentId) {
        return all.stream()
                .filter(p -> p.getParentId() != null && p.getParentId().equals(parentId))
                .peek(p -> p.setChildren(buildTree(all, p.getId())))
                .sorted(Comparator.comparingInt(SysPermission::getSort))
                .collect(Collectors.toList());
    }

    /**
     * 获取全部权限的树形结构（超级管理员或初始化时使用）
     */
    @GetMapping("/tree/all")
    public Result<List<SysPermission>> getAllTree() {
        List<SysPermission> all = permissionService.list();
        List<SysPermission> tree = buildTree(all, 0L);
        return Result.success(tree);
    }
}
